package es.cazadoresmadridejos.beans.dao.advertisement.impl;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.displaytag.pagination.PaginatedList;
import org.displaytag.properties.SortOrderEnum;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

import es.cazadoresmadridejos.beans.dao.advertisement.AdvertisementDao;
import es.cazadoresmadridejos.common.bean.dao.impl.DaoImpl;
import es.cazadoresmadridejos.model.Advertisement;
import es.cazadoresmadridejos.objs.criteria.AdvertisementCriteria;
import es.cazadoresmadridejos.objs.web.Page;
import es.cazadoresmadridejos.objs.web.PaginatedListImpl;

@Repository("advertisementDao")
public class AdvertisementDaoImpl extends DaoImpl<Advertisement> implements AdvertisementDao{

	@Override
	public Advertisement newInstance() {
		return new Advertisement();
	}

	@SuppressWarnings("unchecked")
	@Override
	public PaginatedList findAllPaginated(final Page page,
			final AdvertisementCriteria advertisementCriteria) {
		return (PaginatedList) getHibernateTemplate().execute(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {

				if("id".equals(page.getSort())){
					page.setSort("date");
					page.setSortOrder(SortOrderEnum.DESCENDING);
				}
				
				Map<String,Object> map = new HashMap<String, Object>();
				StringBuilder hql = new StringBuilder();
				StringBuilder hqlCount = new StringBuilder();
				
				hql
				.append("select a ")
				.append(" from Advertisement a ")
				.append(" where 1=1 ");
				
				hqlCount
				.append("select count(a) ")
				.append(" from Advertisement a ")
				.append(" where 1=1 ");
				
				if(advertisementCriteria.getPartnerId() != null){
					hql.append("and a.partner.id = :partnerId");
					hqlCount.append("and a.partner.id = :partnerId");
					map.put("partnerId", advertisementCriteria.getPartnerId());
				}
				if(advertisementCriteria.getStartDate() != null){
					hql.append("and a.date >= :startDate ");
					hqlCount.append("and a.date >= :startDate ");
					map.put("startDate", advertisementCriteria.getStartDate());
				}
				if(advertisementCriteria.getEndDate() != null){
					hql.append(" and a.date <= :endDate ");
					hqlCount.append(" and a.date <= :endDate ");
					map.put("endDate", advertisementCriteria.getEndDate());
				}
				if(advertisementCriteria.getAdvertisementType() != null){
					hql.append(" and a.advertisementType = :advertisementType ");
					hqlCount.append(" and a.advertisementType = :advertisementType ");
					map.put("advertisementType", advertisementCriteria.getAdvertisementType());
				}
				if(advertisementCriteria.getOfferType() != null){
					hql.append(" and a.offerType= :offerType ");
					hqlCount.append(" and a.offerType= :offerType ");
					map.put("offerType", advertisementCriteria.getOfferType());
				}
				if(advertisementCriteria.getAmountFrom() != null){
					hql.append(" and a.amount > :amountFrom ");
					hqlCount.append(" and a.amount >  :amountFrom");
					map.put("amountFrom", advertisementCriteria.getAmountFrom());
				}
				if(advertisementCriteria.getAmountTo() != null){
					hql.append(" and a.amount < :amountTo ");
					hqlCount.append(" and a.amount <  :amountTo ");
					map.put("amountTo", advertisementCriteria.getAmountTo());
				}
				
				if(StringUtils.isNotBlank(advertisementCriteria.getDescription() )){
					String[] descs = advertisementCriteria.getDescription().split(" ");
					hql.append(" and ( ");
					hqlCount.append(" and ( ");
					int count = 0;
					for (String desc: descs) {
						if(count != 0){
							hql.append(" and ");
							hqlCount.append(" and ");
						}
						hql.append(" a.description like :desc" + count);
						hqlCount.append(" a.description like :desc" + count);
						map.put("desc" + count, desc);
						count++;
					}
					hql.append(" ) ");
					hqlCount.append(" ) ");
				}
				hql.append(getSort(page, "a"));

				Query query = session.createQuery(hql.toString());
				Query queryCount = session.createQuery(hqlCount.toString());
				query.setProperties(map);
				queryCount.setProperties(map);
				
				query.setMaxResults(page.getLimit());
				query.setFirstResult(page.getLimit() * (page.getPage() - 1));
				
				return new PaginatedListImpl<Advertisement>(query.list(), page, ((Long) queryCount.uniqueResult()).intValue());
			}
		});
	}

}
